<template>
  <div>
    <el-switch v-model="draggable" active-text="开启拖拽">
    </el-switch>
    <el-tree
      :data="data"
      node-key="catId"
      :props="defaultProps"
      :expand-on-click-node="false"
      :default-expanded-keys="defaultExpandedKeys"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="nodeDrop"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            type="text"
            size="mini"
            v-if="data.children!=null"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => update(data)">
            Update
          </el-button>
          <el-button
            type="text"
            v-if="data.children==null"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog title="添加树形" :visible.sync="dialogFormVisible">
      {{ category }}
      <el-form :model="category">
        <el-form-item label="树形名称" :label-width="formLabelWidth">
          <el-input v-model="category.name"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      draggable:false,
      msg: "分类维护页面",
      data: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      category: {},
      dialogFormVisible: false,
      formLabelWidth: "120px",
      defaultExpandedKeys: [],
      countLevel: 0,
      pid: 0,
      xlevel: 0,
      cupdate: [],
    };
  },
  methods: {
    //实现拖拽成功后执行的目标对象 拿到元素 before、after、inner

    nodeDrop(draggingNode, dropNode, type) {
      console.log(draggingNode, dropNode, type);
      if (type == "before" || type == "after") {
        this.pid = dropNode.data.parentCid;
        this.xlevel = dropNode.level;
        //开始收集
        this.getColletct(dropNode.parent.childNodes);
        if (
          draggingNode.level != dropNode.level &&
          draggingNode.childNodes.length != 0
        ) {
          this.xlevel = this.xlevel + 1;
          this.pid = draggingNode.data.catId;
          this.getColletct(draggingNode.childNodes);
        }
      } else if (type == "inner") {
        this.pid = dropNode.data.catId;
        this.xlevel = dropNode.level + 1;
        //开始收集
        this.getColletct(dropNode.childNodes);
      }

      console.log("最终的对象为:", this.cupdate);
      this.$http({
        url: this.$http.adornUrl(`/product/category/updatetwo`),
        method: "post",
        data: this.$http.adornData(this.cupdate, false),
      }).then(({ data }) => {
        console.log(data);
        if (data.code == 0) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.getTreeList();
          this.defaultExpandedKeys[0] = this.pid;
          this.defaultExpandedKeys[1] = draggingNode.data.parentCid;
          this.cupdate = [];
        }
      });
    },
    //收集
    getColletct(nodes) {
      console.log("目标对象为:", nodes);

      for (var i = 0; i < nodes.length; i++) {
        this.cupdate.push({
          catId: nodes[i].data.catId,
          name: nodes[i].data.name,
          parentCid: this.pid,
          sort: i,
          catLevel: this.xlevel,
        });
      }
    },
    //判断是否可以拖拽
    allowDrop(draggingNode, dropNode, type) {
      this.getCountLevel(draggingNode);

      if (type == "next" || type == "prev") {
        if (this.countLevel == 3 && dropNode.level == 1) {
          return true;
        }
        if (this.countLevel == 2 && dropNode.level != 3) {
          return true;
        }
        if (this.countLevel == 1) {
          return true;
        }
      } else if (type == "inner") {
        if (this.countLevel == 2 && dropNode.level == 1) {
          return true;
        }
        if (this.countLevel == 1 && dropNode.level != 3) {
          return true;
        }
      }
      // console.log(draggingNode, dropNode, type);

      return false;
    },
    //获取等级
    getCountLevel(node) {
      // console.log("被拖拽的对象是:", node);
      this.countLevel = 1;
      if (node.childNodes.length > 0) {
        this.countLevel = 2;
        for (var i in node.childNodes) {
          if (node.childNodes[i].childNodes.length > 0) {
            this.countLevel = 3;
            break;
          }
        }
      }
    },
    // 获取数据列表
    getTreeList() {
      this.$http({
        url: this.$http.adornUrl("/product/category/tlist"),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        console.log(data);
        this.data = data.page;
      });
    },
    update(data) {
      // console.log();
      let id = data.catId;
      this.dialogFormVisible = true;
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${id}`),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        console.log(data);
        this.category = data.category;
      });
    },
    save() {
      let name = "save";
      if (this.category.catId) {
        name = "update";
      }
      this.$http({
        url: this.$http.adornUrl(`/product/category/${name}`),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        console.log(data);
        if (data.code == 0) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
        }
        this.dialogFormVisible = false;
        this.getTreeList();
        this.defaultExpandedKeys[0] = this.category.parentCid;
        this.category = {};
      });
    },
    append(data) {
      console.log(data);
      this.dialogFormVisible = true;
      //   this.category.parentId = data.
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel + 1;
      this.category.sort = 0;
    },

    remove(node, data) {
      console.log(node, data);
      this.$confirm(`确定对[id=${data.catId}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var id = [data.catId];
          this.defaultExpandedKeys[0] = data.parentCid;
          this.$http({
            url: this.$http.adornUrl(`/product/category/delete`),
            method: "post",
            data: this.$http.adornData(id, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getTreeList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
  },
  created() {
    this.getTreeList();
  },
};
</script>

